// 防抖
function debounce(fn, delay = 300) {
  //默认300毫秒
  let timer;
  return function () {
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args); // 改变this指向为调用debounce所指的对象
    }, delay);
  };
}

// 节流
//时间戳写法 立即执行
function throttle(fn, delay) {
  let time = 0;

  return function () {
    let now = Date.now();
    if (now - time > delay) {
      time = Date.now();
      fn.apply(this, arguments);
    }
  };
}

// 定时器写法 延迟执行
function throttle(fn, delay) {
  let flag = true;
  return function () {
    if (!flag) {
      return;
    }
    let args = arguments;
    flag = false;
    timer = setTimeout(() => {
      fn.apply(this, args);
      flag = true;
    }, delay);
  };
}

//两者结合
function throttle(fn, delay) {
  let timer = null;
  let start = Date.now();

  return function () {
    let now = Date.now();
    let remaining = delay - (now - start); //剩余时间
    let args = arguments;
    clearTimeout(timer);
    if (remaining <= 0) {
      fn.apply(this, args);
      start = Date.now();
    } else {
      timer = setTimeout(fn, remaining);
    }
  };
}

function handle() {
  console.log("函数执行");
}

const handleA = throttle(handle, 200);

handleA();
handleA();
handleA();

function a(fn, delay) {
  let time = 0;
  return function () {
    let now = Date.now();
    if (now - time > delay) {
      fn.apply(this, arguments);
      time = Date.now();
    }
  };
}
